<script lang="ts" setup>
import { ref } from 'vue';
import type { FormInstance } from '@arco-design/web-vue/es/form';
import { $fetch } from '@/settings/utils/fetch';
import useNotification from '@/settings/hooks/notification';
import { useI18n } from 'vue-i18n';

const loading = ref(false);
const formData = ref({
  baidu: '',
});
const formRef = ref<FormInstance>();
const { success } = useNotification();
const { t } = useI18n();

const save = async () => {
  const { isSuccess } = await $fetch('/admin/community/createStatisticConfig', {
    method: 'post',
    data: {
      baidu: {
        id: formData.value.baidu,
      },
    },
    loadingStatus: loading,
  });

  if (isSuccess) {
    success(t('settings.notification.success'));
  }
};

const submit = async () => {
  const res = await formRef.value?.validate();

  if (res) {
    return;
  }

  save()
};

const getDetail = async () => {
  const { isSuccess, data } = await $fetch('/admin/community/statisticConfigInfo', {
    method: 'post',
    loadingStatus: loading,
  });

  if (isSuccess) {
    formData.value = {
      baidu: data?.baidu?.id ?? '',
    };
  }
}

getDetail();
</script>

<template>
  <OpenPageSection>
    <OpenGeneralCard>
      <AForm ref="formRef" auto-label-width scroll-to-first-error :model="formData" @submit="submit">
        <AFormItem :label="$t('settings.view.stats.baidu.id')" field="baidu" :rules="[{ maxLength: 32 }]">
          <template #help>
            <i18n-t keypath="settings.view.stats.baidu.help.1" scope="global">
              <template #component>
                <a href="https://tongji.baidu.com/web/help/article?id=175&type=0" target="_blank" class="text-primary-1">{{ $t('settings.view.stats.baidu.help.3') }}</a>
              </template>
            </i18n-t>
            <br>
            {{ $t('settings.view.stats.baidu.help.2') }}
          </template>

          <AInput v-model="formData.baidu" :max-length="32" allow-clear show-word-limit />
        </AFormItem>

        <ADivider />

        <AFormItem>
          <ASpace>
            <AButton html-type="submit" type="primary" :loading="loading">{{ $t('settings.action.submit') }}</AButton>
          </ASpace>
        </AFormItem>
      </AForm>
    </OpenGeneralCard>
  </OpenPageSection>
</template>

<style lang="scss" scoped>
</style>
